﻿using Astronergy.MES.App.Library.Logger;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using mySqlBLL = Astronergy.MES.App.Library.MySQL.BLL;
using mySqlModel = Astronergy.MES.App.Library.MySQL.Model;
using Astronergy.MES.App.Library.LotImageQuery;

namespace Astronergy.MES.App.Library
{
    public class OEMDataConvert
    {
        private EmailHelper _emailHelper = null;
        private FileSystemWatcher _watcher = null;

        public OEMDataConvert()
        {
            try
            {
                LogConsole.InstanceLogConsole.Init(false, true, Constant.LogPath + "\\Log\\");
            }
            catch { }
            _emailHelper = new EmailHelper(Constant.MailServer, Constant.MailUserName, Constant.MailPassword, Constant.MailFrom, Constant.MailSender, Constant.MailTo, Constant.MailCc);
            FileWatcher();
        }

        public void OpenWatcher()
        {
            _watcher.EnableRaisingEvents = true;
        }

        public void CloseWatcher()
        {
            _watcher.EnableRaisingEvents = false;
        }

        /// <summary>
        /// 数据文件监视
        /// </summary>
        private void FileWatcher()
        {
            _watcher = new FileSystemWatcher();

            //初始化监听
            _watcher.BeginInit();
            _watcher.Filter = Constant.DataFileSuffix;
            _watcher.Path = Constant.MonitorPath;
            _watcher.Created += new FileSystemEventHandler(OnCreated);
            _watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite;
            //结束初始化
            _watcher.EndInit();
        }

        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Created)
            {
                DataConvert(e.FullPath);
            }
        }

        private void DataConvert(string filePath)
        {
            try
            {
                //异常信息存储
                string warningMsg = "";
                //获取数据文件中的数据
                DataSet dsSourceData = GetExcelData(filePath, ref warningMsg);
                //判断数据文件中是否存在有效数据
                if (dsSourceData != null
                    && dsSourceData.Tables.Count > 0
                    && dsSourceData.Tables[0].Rows.Count > 0)
                {
                    //数据转移到MySQL数据库
                    foreach (DataRow dr in dsSourceData.Tables[0].Rows)
                    {
                        try
                        {
                            if (!MySqlImport(dr, ref warningMsg))
                            {
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.Message);
                            warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.StackTrace);
                            break;
                        }
                    }
                    _emailHelper.SendEMail(string.Format("{0}导入完成", Constant.Location), string.Format("文件【{0}】数据导入完成！",filePath));
                }
                else
                {
                    warningMsg = string.Format("未找到有效数据！请确认文件【{0}】中数据表是否符合要求~", filePath);
                }

                if (!string.IsNullOrWhiteSpace(warningMsg))
                {
                    _emailHelper.SendEMail(string.Format("{0}异常信息", Constant.Location), warningMsg);
                }
            }
            catch (Exception ex)
            {
                object state = new
                {
                    msg = ex.Message,
                    type = EunmMsgType.Warning
                };

                ThreadPool.QueueUserWorkItem(Go, state);
            }

        }

        /// <summary>
        /// 根据数据文件路径获取数据信息
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>数据文件中的数据</returns>
        private DataSet GetExcelData(string filePath, ref string warningMsg)
        {
            DataSet dtResults = null;
            try
            {
                ExcelHelper excelHelper = new ExcelHelper();
                dtResults = excelHelper.ExcelToDS(filePath);
            }
            catch (Exception ex)
            {
                warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.Message);
                warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.StackTrace);

                _emailHelper.SendEMail(string.Format("{0}异常信息", Constant.Location), warningMsg);

            }
            return dtResults;
        }

        /// <summary>
        /// 将第三方数据导入到MySQL数据库
        /// </summary>
        /// <param name="dr">一个批次完整的数据</param>
        private bool MySqlImport(DataRow dr, ref string warningMsg)
        {
            bool isSuccess = true;
            try
            {
                mySqlModel.pro_lot proLotModel = new mySqlModel.pro_lot();
                mySqlModel.pro_lot_test_data proTestDataModel = new mySqlModel.pro_lot_test_data();

                string lotNumber = Convert.ToString(dr["Lot_Number"]);
                string productModel = Convert.ToString(dr["ProductModel"]);
                DateTime createTime = DateTime.Now;

                proLotModel.LOT_NO = lotNumber;
                proLotModel.VERSION_NO = 1;
                proLotModel.BARCODE = lotNumber;
                proLotModel.PART_NUMBER = lotNumber;
                proLotModel.ORDER_NUMBER = lotNumber;
                proLotModel.PRODUCT_ID = productModel;
                proLotModel.PRODUCT_MODEL = productModel;
                proLotModel.LOCATION = Constant.Location;
                proLotModel.CREATOR = "sys";
                proLotModel.CREATE_TIME = DateTime.TryParse(Convert.ToString(dr["CREATE_TIME"]), out createTime) ? createTime : DateTime.Now;
                proLotModel.IS_USED = "Y";

                proTestDataModel.LOT_NUMBER = lotNumber;
                proTestDataModel.VERSION_NO = 1;
                proTestDataModel.TTIME = DateTime.TryParse(Convert.ToString(dr["CREATE_TIME"]), out createTime) ? createTime : DateTime.Now;
                proTestDataModel.EL_IMAGE = UploadImageNew(createTime, lotNumber, ref warningMsg);
                proTestDataModel.IV_IMAGE = "";

                decimal tempDecimal = 0.00M;
                proTestDataModel.PMAX = Decimal.TryParse(Convert.ToString(dr["PMAX"]), out tempDecimal) ? tempDecimal : 0.00M;
                proTestDataModel.ISC = Decimal.TryParse(Convert.ToString(dr["ISC"]), out tempDecimal) ? tempDecimal : 0.00M;
                proTestDataModel.IPM = Decimal.TryParse(Convert.ToString(dr["IPM"]), out tempDecimal) ? tempDecimal : 0.00M;
                proTestDataModel.VOC = Decimal.TryParse(Convert.ToString(dr["VOC"]), out tempDecimal) ? tempDecimal : 0.00M;
                proTestDataModel.VPM = Decimal.TryParse(Convert.ToString(dr["VPM"]), out tempDecimal) ? tempDecimal : 0.00M;
                proTestDataModel.IS_USED = "Y";



                AddOrUpdateProLot(proLotModel);
                AddOrUpdateProTestData(proTestDataModel);
            }
            catch (Exception ex)
            {
                warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.Message);
                warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.StackTrace);

                isSuccess = false;
            }
            return isSuccess;
        }

        /// <summary>
        /// 添加或更新批次数据
        /// </summary>
        /// <param name="proLotModel">批次数据模型</param>
        private void AddOrUpdateProLot(mySqlModel.pro_lot proLotModel)
        {
            try
            {
                mySqlBLL.pro_lot proLotBll = new mySqlBLL.pro_lot();
                bool isExists = proLotBll.Exists(proLotModel.LOT_NO, 1, Constant.Location);
                if (isExists)
                {
                    proLotBll.Update(proLotModel);
                }
                else
                {
                    proLotBll.Add(proLotModel);
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 新增或更新批次测试数据信息
        /// </summary>
        /// <param name="proTestDataModel">批次测试数据模型</param>
        private void AddOrUpdateProTestData(mySqlModel.pro_lot_test_data proTestDataModel)
        {
            try
            {
                mySqlBLL.pro_lot_test_data proTestDataBll = new mySqlBLL.pro_lot_test_data();
                bool isExists = proTestDataBll.Exists(proTestDataModel.LOT_NUMBER, 1);
                if (isExists)
                {
                    proTestDataBll.Update(proTestDataModel);
                }
                else
                {
                    proTestDataBll.Add(proTestDataModel);
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="testTime">测试时间</param>
        private string UploadImage(DateTime testTime, string lotNumber, ref string warningMsg)
        {
            string returnPath = "";

            string sourcePath, aimPath, sourceFilePath, aimFilePath;
            try
            {
                //1、拼接原图片地址路径判断否存在
                sourcePath = string.Format(Constant.ImageSourcePathFormat, testTime);
                sourceFilePath = string.Format("{0}\\{1}.jpg", sourcePath, lotNumber);
                aimPath = string.Format(Constant.ImageStoragePathFormat, testTime);
                aimFilePath = string.Format("{0}\\{1}.jpg", aimPath, lotNumber);
                //判断路径是否存在
                if (Directory.Exists(sourcePath) && File.Exists(sourceFilePath))
                {
                    if (!Directory.Exists(aimPath))
                    {
                        Directory.CreateDirectory(aimPath);
                    }
                    //2、压缩保存图片
                    ImageHelper imageHelper = new ImageHelper();
                    imageHelper.SaveCompressPic(sourceFilePath, aimFilePath);
                    //3、返回站点地址
                    returnPath = string.Format(Constant.ImageSiteUrlFormat, testTime, lotNumber);
                }
                else
                {
                    string msg = string.Format("图片 【{0}】在路径【{1}】 未找到", lotNumber, sourceFilePath);
                    warningMsg = string.Format("{0}\r\n{1}", warningMsg, msg);
                    object state = new
                    {
                        msg = msg,
                        type = EunmMsgType.Warning
                    };

                    ThreadPool.QueueUserWorkItem(Go, state);
                }

            }
            catch (Exception ex)
            {
                warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.Message);
                warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.StackTrace);
            }
            return returnPath;
        }


        ILotImageQueryService client = new LotImageQueryServiceClient();
        /// <summary>
        /// 临时改动，不需要知道配置原路径，调用接口即可获得
        /// </summary>
        /// <param name="testTime"></param>
        /// <param name="lotNumber"></param>
        /// <param name="warningMsg"></param>
        /// <returns></returns>
        private string UploadImageNew(DateTime testTime, string lotNumber, ref string warningMsg)
        {
            string returnPath = "";

            string sourcePath, aimPath, sourceFilePath, aimFilePath;
            try
            {
                

                //1、拼接原图片地址路径判断否存在
                //sourcePath = string.Format(Constant.ImageSourcePathFormat, testTime);
                //sourceFilePath = string.Format("{0}\\{1}.jpg", sourcePath, lotNumber);
                sourceFilePath=client.GetLotImagePath(lotNumber, LotImageType.EL);

                aimPath = string.Format(Constant.ImageStoragePathFormat, testTime);
                aimFilePath = string.Format("{0}\\{1}.jpg", aimPath, lotNumber);
                //判断路径是否存在
                if (File.Exists(sourceFilePath))
                {
                    if (!Directory.Exists(aimPath))
                    {
                        Directory.CreateDirectory(aimPath);
                    }
                    //2、压缩保存图片
                    ImageHelper imageHelper = new ImageHelper();
                    imageHelper.SaveCompressPic(sourceFilePath, aimFilePath);
                    //3、返回站点地址
                    returnPath = string.Format(Constant.ImageSiteUrlFormat, testTime, lotNumber);
                }
                else
                {
                    string msg = string.Format("图片 【{0}】在路径【{1}】 未找到", lotNumber, sourceFilePath);
                    warningMsg = string.Format("{0}\r\n{1}", warningMsg, msg);
                    object state = new
                    {
                        msg = msg,
                        type = EunmMsgType.Warning
                    };

                    ThreadPool.QueueUserWorkItem(Go, state);
                }

            }
            catch (Exception ex)
            {
                warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.Message);
                warningMsg = string.Format("{0}\r\n{1}", warningMsg, ex.StackTrace);
            }
            return returnPath;
        }

        private void Go(object state)
        {
            try
            {
                object msg = state.GetType().GetProperty("msg").GetValue(state);
                object type = state.GetType().GetProperty("type").GetValue(state);
                LogLightConsole.WriteLog(msg.ToString(), (EunmMsgType)type);
            }
            catch { }
        }
    }
}
